package cn.com.rexen.rplus.controller;

import cn.com.rexen.rplus.sa.entity.Apps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 基础Controller类.
 * Created by libo on 2014/5/4.
 *
 * @author libo .
 */
public class ControllerSupport {

    /**
     * 日志.
     */
    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 当前应用.
     */
    private Apps apps;

    /**
     * 获取当前应用实例.
     *
     * @return 当前应用.
     */
    public Apps getApps() {
        if (apps == null) {
            apps = new Apps();
            apps.setId("rplus");
            apps.setName("Rplus快速开发运行平台");
        }
        return apps;
    }

    /**
     * 绑定日期格式.
     *
     * @param binder WebDataBinder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(Integer.class, new CustomNumberEditor(Integer.class, true));
        binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, true));
        binder.registerCustomEditor(MultipartFile.class, new ByteArrayMultipartFileEditor());
    }

    /**
     * 用于显示响应的错误信息.
     *
     * @param code     http 响应码.
     * @param errorMsg 响应的错误 信息.
     * @param response http响应.
     */
    protected void responseError(int code, String errorMsg, HttpServletResponse response) {
        response.setStatus(code);
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(errorMsg.getBytes("UTF-8"));
            outputStream.flush();
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error(e.getMessage());
                }
            }
        }
    }

}
